package model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import controller.DBmanager;


public class BidDAO {
	
	private String sqlSelectBids	=	"SELECT * FROM BIDS WHERE auction=? ORDER BY bid DESC";
	private String sqlCreateBid		=	"INSERT INTO BIDS(auction, bidder, bid, bdate) VALUES(?,?,?,?)";
	private String sqlDeleteBids	=	"DELETE FROM BIDS WHERE auction=?";
	
	private Connection			con			=	null;
	private PreparedStatement	psSelect	=	null;
	private PreparedStatement	psCreate 	=	null;
	private PreparedStatement	psDelete	=	null;
	
	public BidDAO(){
		con = DBmanager.getInstance().getConnection();
		try{
			psSelect = con.prepareStatement(sqlSelectBids);
			psCreate = con.prepareStatement(sqlCreateBid);
			psDelete = con.prepareStatement(sqlDeleteBids);
		}catch(SQLException e){
			printSQLException(e);
		}
	}
	
	public ArrayList<BidBean> selectBids(int auction){
		ArrayList<BidBean> beans = new ArrayList<BidBean>();
		try{
			psSelect.clearParameters();
			
			psSelect.setInt(1, auction);
			
			ResultSet result = psSelect.executeQuery();
			while(result.next()){
				BidBean bean = new BidBean();
				bean.setAll(result.getInt("auction"), result.getInt("bidder"), result.getDouble("bid"), result.getTimestamp("bdate"));
				beans.add(bean);
			}
		}catch(SQLException e){
			printSQLException(e);
		}
		return beans;
	}
	
	public double getMaxBid(int auction){
		ArrayList<BidBean> beans = selectBids(auction);
		double maxbid = 0;
		for(BidBean b: beans){
			if(b.getBid() > maxbid){
				maxbid = b.getBid();
			}
		}
		return maxbid;
	}
	
	public void newBid(int auction, int bidder, double bid, Timestamp date){
		try{
			psCreate.clearParameters();
			
			psCreate.setInt(1, auction);
			psCreate.setInt(2, bidder);
			psCreate.setDouble(3, bid);
			psCreate.setTimestamp(4, date);
			
			psCreate.executeUpdate();
		}catch(SQLException e){
			printSQLException(e);
		}
	}
	
	public void deleteBids(int auction){
		try{
			psDelete.clearParameters();
			
			psDelete.setInt(1, auction);
			
			psDelete.executeUpdate();
		}catch(SQLException e){
			printSQLException(e);
		}
	}
	
	private void printSQLException(SQLException se) {
		while(se != null) {
			se.printStackTrace();
			
			se = se.getNextException();
		}
	}
	
}
